<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>大模型矩阵·智能插图生成器</title>
    
    <!-- 国内CDN资源 -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .upload-area {
            border: 3px dashed #dee2e6;
            border-radius: 15px;
            padding: 60px;
            text-align: center;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
            margin: 20px 0;
        }
        
        .upload-area:hover {
            border-color: #667eea;
            background: rgba(255, 255, 255, 0.95);
            transform: translateY(-2px);
        }
        
        .upload-area.dragover {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.1);
        }
        
        .task-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 15px;
            transition: transform 0.2s;
        }
        
        .task-card:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }
        
        .progress-custom {
            height: 8px;
            border-radius: 10px;
        }
        
        .status-icon {
            font-size: 1.2em;
            margin-right: 8px;
        }
        
        .preview-image {
            max-width: 100%;
            height: 150px;
            object-fit: cover;
            border-radius: 8px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="text-center mb-5">
            <h1 class="text-white mb-3">
                <i class="fas fa-magic me-3"></i>
                大模型矩阵·智能插图生成器
            </h1>
            <p class="text-white-50">AI驱动的Word文档智能插图生成系统</p>
        </div>

        <!-- 上传区域 -->
        <div class="upload-area" id="uploadArea">
            <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
            <h4 class="text-muted mb-3">拖拽Word文档到此处</h4>
            <p class="text-muted">或</p>
            <input type="file" id="fileInput" multiple accept=".docx" class="d-none">
            <button class="btn btn-primary" onclick="document.getElementById('fileInput').click()">
                <i class="fas fa-folder-open me-2"></i>选择文件
            </button>
        </div>

        <!-- 任务列表 -->
        <div id="taskList" class="mt-4" style="display: none;">
            <h3 class="text-white mb-3">处理任务</h3>
            <div id="taskContainer"></div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    
    <script>
        const API_BASE = 'http://localhost:8000';
        let tasks = [];

        // 上传区域事件
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            handleFiles(e.dataTransfer.files);
        });

        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });

        async function handleFiles(files) {
            const formData = new FormData();
            let hasDocx = false;
            
            for (let file of files) {
                if (file.name.endsWith('.docx')) {
                    formData.append('files', file);
                    hasDocx = true;
                }
            }
            
            if (!hasDocx) {
                alert('请上传Word文档（.docx格式）');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/upload`, {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                // 开始处理每个任务
                for (let file of data.uploaded_files) {
                    tasks.push(file);
                    startProcessing(file.task_id);
                }
                
                document.getElementById('taskList').style.display = 'block';
                renderTasks();
                
            } catch (error) {
                console.error('上传失败:', error);
                alert('上传失败，请重试');
            }
        }

        async function startProcessing(taskId) {
            try {
                await fetch(`${API_BASE}/process/${taskId}`, {
                    method: 'POST'
                });
                
                // 开始轮询状态
                pollStatus(taskId);
                
            } catch (error) {
                console.error('处理启动失败:', error);
            }
        }

        async function pollStatus(taskId) {
            const interval = setInterval(async () => {
                try {
                    const response = await fetch(`${API_BASE}/status/${taskId}`);
                    const data = await response.json();
                    
                    // 更新任务状态
                    const taskIndex = tasks.findIndex(t => t.task_id === taskId);
                    if (taskIndex !== -1) {
                        tasks[taskIndex].status = data.status;
                        tasks[taskIndex].progress = data.progress || 0;
                        tasks[taskIndex].total_paragraphs = data.total_paragraphs || 0;
                        tasks[taskIndex].processed_paragraphs = data.processed_paragraphs || 0;
                    }
                    
                    renderTasks();
                    
                    if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {
                        clearInterval(interval);
                    }
                    
                } catch (error) {
                    console.error('获取状态失败:', error);
                    clearInterval(interval);
                }
            }, 1000);
        }

        function renderTasks() {
            const container = document.getElementById('taskContainer');
            container.innerHTML = '';
            
            tasks.forEach(task => {
                const card = createTaskCard(task);
                container.appendChild(card);
            });
        }

        function createTaskCard(task) {
            const card = document.createElement('div');
            card.className = 'task-card p-4';
            
            let statusIcon = '';
            let statusClass = '';
            let actionButtons = '';
            
            switch(task.status) {
                case 'pending':
                    statusIcon = '<i class="fas fa-clock text-warning status-icon"></i>';
                    statusClass = 'text-warning';
                    break;
                case 'processing':
                    statusIcon = '<i class="fas fa-spinner fa-spin text-primary status-icon"></i>';
                    statusClass = 'text-primary';
                    break;
                case 'completed':
                    statusIcon = '<i class="fas fa-check-circle text-success status-icon"></i>';
                    statusClass = 'text-success';
                    actionButtons = `
                        <button class="btn btn-success btn-sm" onclick="downloadResults('${task.task_id}')">
                            <i class="fas fa-download me-1"></i>下载结果
                        </button>
                    `;
                    break;
                case 'failed':
                    statusIcon = '<i class="fas fa-exclamation-circle text-danger status-icon"></i>';
                    statusClass = 'text-danger';
                    break;
                case 'cancelled':
                    statusIcon = '<i class="fas fa-times-circle text-secondary status-icon"></i>';
                    statusClass = 'text-secondary';
                    break;
            }
            
            let progressBar = '';
            if (task.status === 'processing' && task.total_paragraphs > 0) {
                const progress = (task.processed_paragraphs / task.total_paragraphs) * 100;
                progressBar = `
                    <div class="mt-3">
                        <div class="d-flex justify-content-between mb-1">
                            <small>处理进度</small>
                            <small>${task.processed_paragraphs}/${task.total_paragraphs} 段落</small>
                        </div>
                        <div class="progress progress-custom">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" 
                                 role="progressbar" 
                                 style="width: ${progress}%">
                            </div>
                        </div>
                    </div>
                `;
            }
            
            card.innerHTML = `
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <h5 class="mb-2">${task.filename}</h5>
                        <p class="mb-0 ${statusClass}">
                            ${statusIcon}
                            ${getStatusText(task.status)}
                        </p>
                        ${progressBar}
                    </div>
                    <div>
                        ${actionButtons}
                        ${task.status === 'processing' ? `
                            <button class="btn btn-outline-danger btn-sm ms-2" onclick="cancelTask('${task.task_id}')">
                                <i class="fas fa-stop"></i>
                            </button>
                        ` : ''}
                    </div>
                </div>
            `;
            
            return card;
        }

        function getStatusText(status) {
            const statusMap = {
                'pending': '等待处理',
                'processing': '处理中',
                'completed': '已完成',
                'failed': '处理失败',
                'cancelled': '已取消'
            };
            return statusMap[status] || status;
        }

        async function downloadResults(taskId) {
            try {
                const response = await fetch(`${API_BASE}/download/${taskId}`);
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${taskId}_results.zip`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } else {
                    alert('下载失败');
                }
            } catch (error) {
                console.error('下载失败:', error);
                alert('下载失败，请重试');
            }
        }

        async function cancelTask(taskId) {
            try {
                await fetch(`${API_BASE}/cancel/${taskId}`, {
                    method: 'DELETE'
                });
            } catch (error) {
                console.error('取消失败:', error);
            }
        }
    </script>
</body>
</html>
